package com.wanli.agent.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wanli.agent.R;
import com.wanli.agent.base.DataCallBack;
import com.wanli.agent.bean.EBankIndustryListBean;
import com.wanli.agent.homepage.adapter.ChooseIndustryListAdapter;
import com.wanli.agent.homepage.model.HomePageModelImpl;
import com.wanli.agent.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Author:HWC
 */
public class ChooseIndustryDialog extends DialogFragment {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.edit_search)
    EditText editSearch;
    @BindView(R.id.view_cancel)
    View viewCancel;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    private Activity mActivity;
    private Dialog dialog;
    private List<EBankIndustryListBean.DataBean> beanList;
    private List<EBankIndustryListBean.DataBean> allBeanList;
    private OnCallBackListener onCallBackListener;

    public void setOnCallBackListener(OnCallBackListener onCallBackListener) {
        this.onCallBackListener = onCallBackListener;
    }

    private ChooseIndustryListAdapter listAdapter;
    private String mcc_type;
    private String keyword = "";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initWindow();
        View view = inflater.inflate(R.layout.dialog_choose_industry, null);
        ButterKnife.bind(this, view);
        mActivity = getActivity();
        initView();
        requestData();
        return view;
    }


    public static ChooseIndustryDialog newInstance(String mcc_type) {
        Bundle args = new Bundle();
        ChooseIndustryDialog fragment = new ChooseIndustryDialog();
        args.putString("mcc_type", mcc_type);
        fragment.setArguments(args);
        return fragment;
    }

    //    初始化请求
    private void initView() {
        mcc_type = getArguments().getString("mcc_type");
        beanList = new ArrayList<>();
        allBeanList = new ArrayList<>();
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        listAdapter = new ChooseIndustryListAdapter(beanList);
        recyclerView.setAdapter(listAdapter);

        listAdapter.setOnCallBackListener(position -> {
            if (onCallBackListener != null) {
                onCallBackListener.onCallBack(beanList.get(position).getText(), beanList.get(position).getCode());
            }
            dismiss();
        });

        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(keyword)) {
                        refreshData();
                    }
                    return true;
                }
                return false;
            }
        });
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                keyword = editSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(keyword)) {
                    viewCancel.setVisibility(View.VISIBLE);
                } else {
                    viewCancel.setVisibility(View.GONE);
                }
                refreshData();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    public void requestData() {
        new HomePageModelImpl().requestIndustryType(mcc_type, new DataCallBack<EBankIndustryListBean>() {
            @Override
            public void onSuccessful(EBankIndustryListBean bean) {
                allBeanList.addAll(bean.getData());
                beanList.addAll(allBeanList);
                listAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    //设置window属性
    private void initWindow() {
        //去掉dialog的标题
        dialog = this.getDialog();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        Window window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        window.getAttributes().windowAnimations = R.style.commomDialog;
        window.setAttributes(lp);
        window.setBackgroundDrawable(new ColorDrawable());
    }

    @OnClick({R.id.view_cancel, R.id.tv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.view_cancel:
                editSearch.setText("");
                keyword = "";
                refreshData();
                break;
            case R.id.tv_search:
                if (TextUtils.isEmpty(keyword)) {
                    ToastUtil.showShort("请输入搜索内容");
                    return;
                }
                refreshData();
                break;
        }
    }

    public void refreshData() {
        beanList.clear();
        if (!TextUtils.isEmpty(keyword)) {
            for (EBankIndustryListBean.DataBean dataBean : allBeanList) {
                if ((dataBean.getCode() + dataBean.getText()).contains(keyword)
                        || keyword.equals(dataBean.getCode())
                        || keyword.equals(dataBean.getText())) {
                    beanList.add(dataBean);
                }
            }
        } else {
            beanList.addAll(allBeanList);
        }
        listAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    public interface OnCallBackListener {
        void onCallBack(String name, String code);
    }
}
